import json
import re
import urllib
from email.utils import parsedate_to_datetime

import pandas as pd
import io
import pytz
import datetime
import requests
import base64

import requests
from flask import request, make_response


# 提取字符串中的整数如果字符串中出现千或者万，则乘以1000或者10000
def parse_number(input_str):
    if input_str is None or input_str.strip() == '':
        return ''
    num_match = re.search(r'\d+\.?\d*', input_str)
    if num_match:
        num = int(num_match.group())

        if '千' in input_str:
            num *= 1000
        elif '万' in input_str:
            num *= 10000

        return str(num)
    return ''


# 根据label获取value
def parse_label_value(arr, label):
    for item in arr:
        if item['label'] == label:
            return item['value']
    return ''


# 比较label输出相似度最高的value
def compare_labels(str_input, array):
    if str_input is None:
        return None
    max_count = 0
    result_value = None

    for obj in array:
        label = obj['label']
        value = obj['value']

        common_chars = set(str_input) & set(label)
        if len(common_chars) > max_count:
            max_count = len(common_chars)
            result_value = value
            if max_count == len(label):
                break

    return result_value


# 比较label输出相似度最高的value和label
def compare_labels_pro(str_input, array):
    if str_input is None:
        return None
    max_count = 0
    result_value = ''
    result_label = ''

    for obj in array:
        label = obj['label']
        value = obj['value']

        common_chars = set(str_input) & set(label)
        if len(common_chars) > max_count:
            max_count = len(common_chars)
            result_value = value
            result_label = label
            if max_count == len(label):
                break

    return {
        'value': result_value,
        'label': result_label
    }


# 将图片url转为base64
def url_to_base64(url):
    response = requests.get(url)
    return 'data:image/jpeg;base64,' + base64.b64encode(response.content).decode('utf-8')


# 根据serial_no和dcc_token获取DCC数据

def dcc_book_detail(serial_no, dcc_token):
    book_details = requests.get(
        f'http://open.cloudycentury.net:6600/prod-api/bookinfo/infoBase/query/{serial_no}',
        headers={
            'Authorization': f'Bearer {dcc_token}',
        },
        verify=False,
    )
    book_details_json = json.loads(book_details.text)
    return book_details_json


# 匹配字符串中的书号
def extract_substring(text):
    # 正则表达式模式，匹配以 978 开头，后面跟随任意数量的数字直到字符串结尾
    pattern = r'978\d*'

    # 使用re.search查找第一个匹配的子字符串
    match = re.search(pattern, text)

    # 如果找到了匹配的子字符串，返回它
    if match:
        return match.group()
    else:
        return None


# 通过图片url获取图片的信息
def get_file_content(image_url):
    def format_last_modified(last_modified_str):
        # 解析Last-Modified字符串为datetime对象
        dt_gmt = parsedate_to_datetime(last_modified_str)

        # 将GMT时间转换到中国标准时间
        china_tz = pytz.timezone('Asia/Shanghai')
        dt_cst = dt_gmt.astimezone(china_tz)

        # 格式化datetime对象为特定格式字符串
        formatted_date_str = dt_cst.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (中国标准时间)')
        return formatted_date_str

    res = requests.get(image_url)
    file_name = image_url.split('/')[-1]
    last_modified_str = res.headers['last-modified']
    type = res.headers['content-type']
    if last_modified_str:
        last_modified_str = format_last_modified(last_modified_str)
    else:
        last_modified_str = 'Fri Jan 26 2024 09:06:16 GMT+0800 (中国标准时间)'
    size = res.headers['content-length']
    if size:
        size = str(size)
    else:
        size = '9999'
    # 检查请求是否成功
    if res.status_code == 200:
        return {'content': res.content, 'size': size,
                'lastModifiedDate': last_modified_str, 'file_name': file_name, 'type': type}
    else:
        return None


# 导出Excel模板
def send_excel_template(data, __filename):
    df = pd.DataFrame(data)
    # 将DataFrame写入到一个Excel文件的内存中
    output = io.BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df.to_excel(writer, index=False, sheet_name='Sheet1')

    # 设置文件指针到开始位置
    output.seek(0)
    filename = __filename + '_' + datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.xlsx'
    encoded_filename = urllib.parse.quote(filename)
    # 创建一个响应对象并发送文件
    response = make_response(output.read())
    response.headers['Content-Disposition'] = f"attachment; filename*=UTF-8''{encoded_filename}"
    response.headers['Content-type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    return response
